import React, { useContext, useEffect, useState } from "react";
import ReactQuill from 'react-quill';
import { UserContext } from "../context/userContext";
import { useNavigate } from "react-router-dom";
import {Space, Button, Modal, Switch, DatePicker, TextArea, Input, Form} from 'antd-mobile'
import dayjs from "dayjs"
import axios from "axios";
import "./create.css"
import 'react-quill/dist/quill.snow.css';

const CreatePost = () => {
  const [title, setTitle] = useState('');
  const [description, setDescription] = useState('');
  const [error, setError] = useState('');
  const [agree, setAgree] = useState(true);
  const [email, setEmail] = useState('');
  const [wages, setWages] = useState('');
  const [contact, setContact] = useState('')
  const [deadline, setDeadline] = useState('')
  const [pickerVisible, setPickerVisible] = useState(false);
  const navigate = useNavigate();
  const { currentUser } = useContext(UserContext);
  const token = currentUser?.token;
  useEffect(() => {
    if (!token) {
      navigate('/login');
    }
  }, [token, navigate]);

  const createPost = async (e) => {
    e.preventDefault();
    console.log('create post')
    const postData = new FormData();
    postData.set('title', title);
    postData.set('contact', contact);
    postData.set('description', description);
    postData.set('agree', agree);
    postData.set('email', email);
    postData.set('wages', wages?wages:"免费");
    postData.set('deadline', deadline)
    console.log(postData)
    try {
      const response = await axios.post(`${process.env.REACT_APP_BASE_URL}/posts`, postData, { withCredentials: true, headers: { Authorization: `Bearer ${token}` } });

      if (response.status === 201) {
        Modal.alert({
          title: '项目提交成功',
          content: '我们正在审核项目信息，审核结果将会尽快通知您，请关注电话或短信通知',
          showCloseButton: true,
        })
        return navigate('/');
      }
    } catch (err) {
      setError(err.response.data.message);
    }
  };

  return (
      <section className="create-post">
        <div className="box_3 flex-row">
          <div className="box_4 flex-col"/>
          <div className="text-wrapper_1">
            <span className="text_3">*</span>
            <span className="text_4">您的需求</span>
          </div>
        </div>
        <form className="form create-post__form" >
          <div className="group_2 flex-col">
            <div className="text-wrapper_2">
              <span className="text_8">*</span>
              <span className="text_9">需求标题</span>
            </div>
            <div className="text-wrapper_4 flex-row justify-between">
              <Input value={title} onChange={(value) => setTitle(value)} type="text" name="title"
                     placeholder="简要概括需求内容"/>
            </div>
            <div className="text-wrapper_2">
              <span className="text_8">*</span>
              <span className="text_9">需求详情</span>
            </div>
            <div className="text-wrapper_5 flex-row justify-between">
              <TextArea
                  placeholder='详细描述需求便于更好理解项目要求'
                  maxLength={200}
                  minLength={100}
                  rows={3}
                  value={description}
                  onChange={(val) => setDescription(val)}
                  showCount
              />
            </div>
            </div>
        </form>

        <div className="box_3 flex-row">
          <div className="box_4 flex-col"/>
          <div className="text-wrapper_1">
            <span className="text_3">*</span>
            <span className="text_4">联系方式</span>
          </div>
        </div>
        <div className="group_3 flex-col">
          <div className="text-wrapper_4 flex-row justify-between">
            <span className="text_11">电话</span>
            <Input value={contact} onChange={(val)=>setContact(val)} className="text_12" type="text" placeholder="输入电话号码（成功匹配后联系沟通）"></Input>
          </div>

          <div className="text-wrapper_3 flex-row justify-between">
            <span className="text_11">允许电话沟通</span>
            <Switch onChange={checked => setAgree(checked)} defaultChecked/>
          </div>

          <div className="text-wrapper_4 flex-row justify-between">
            <span className="text_11">电子邮箱</span>
            <Input value={email} onChange={(val)=>setEmail(val)}  className="text_12" type="text" placeholder="输入邮箱（成功匹配后联系沟通）"></Input>
          </div>
        </div>

        <div className="box_3 flex-row">
          <div className="box_4 flex-col"/>
          <div className="text-wrapper_1">
            <span className="text_3"></span>
            <span className="text_4">任务设计</span>
          </div>
        </div>

        <div className="group_3 flex-col">
          <div className="text-wrapper_4 flex-row justify-between">
            <span className="text_11">任务赏金</span>
            <Input value={wages} onChange={(val)=>setWages(val)} className="text_12" type="text" placeholder="默认免费"></Input>
          </div>

          <div onClick={() => {
            setPickerVisible(true)
          }} className="text-wrapper_4 flex-row justify-between">
            <span className="text_11">投稿截止</span>
            <DatePicker
                className="text_12"
                visible={pickerVisible}
                onConfirm={(value)=>{
                  setDeadline(dayjs(value).format('YYYY-MM-DD'))
                }}
                onClose={() => {
                  setPickerVisible(false)
                }}
            >
              {value => value ? dayjs(value).format('YYYY-MM-DD') : '请选择日期'}
            </DatePicker>
          </div>
        </div>
        <Space className="bottom"  justify="between">
          <Space wrap>
          <span className="text_11">总金额</span>
          <span className="text_3">{wages?wages:'免费'}</span>
          </Space>
          <Button block
                  onClick={createPost}
                  style={{"--background-color":'rgba(80, 62, 157, 1)', "--text-color":'rgba(255, 255, 255, 1)', "--border-radius":'12px'}}
                  shape='rectangular' color='primary'>
            确定发布
          </Button>
        </Space>
      </section>
  );
};

export default CreatePost;

